package com.ifacebox.client.tools;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Arrays;
import java.util.Map;

/**
 * @author znn
 */
public class SspUploadToolsGui extends JFrame implements ActionListener {
    private JFileChooser jFileChooser;
    private final JToolBar jToolBar;
    private JButton jButtonChooser, jButtonUpload, jButtonConfig;
    private final JTable jTableUpload;
    private DefaultTableModel tableModelUpload;
    private final JLabel jLabelStatus;
    private JPanel jPanelConfig;
    private JTextField jTextFieldCookie, jTextFieldToken, jTextFieldOpUser, jTextFieldOptName, jTextFieldLogId, jTextFieldAppKey, jTextFieldSign;
    private SspUploadConfig config;

    public SspUploadToolsGui() {
        super.setTitle("百度聚屏监播上传工具 - 监播文件目录名规则（年-月-日,订单号）");
        super.setIconImage(new ImageIcon(SspConstants.LOGO_URL).getImage());
        super.setPreferredSize(new Dimension(800, 600));
        super.setLayout(new BorderLayout());
        super.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        super.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        super.add(jToolBar = new JToolBar(), BorderLayout.NORTH);
        super.add(new JScrollPane(jTableUpload = new JTable()), BorderLayout.CENTER);
        super.add(jLabelStatus = new JLabel(String.format(SspUploadConstants.UPLOAD_STATUS, "", "", 0, 0, 0)), BorderLayout.SOUTH);
        this.initComponents();
        super.pack();
        super.setLocationRelativeTo(null);
    }

    public void initComponents() {
        jFileChooser = new JFileChooser();
        jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        jToolBar.add(jButtonChooser = new JButton("选择监播文件"));
        jToolBar.add(jButtonUpload = new JButton("上传监播文件"));
        jToolBar.add(jButtonConfig = new JButton("参数配置"));
        jButtonChooser.addActionListener(this);
        jButtonUpload.addActionListener(this);
        jButtonConfig.addActionListener(this);
        jTableUpload.setRowHeight(30);
        jTableUpload.setModel(tableModelUpload = new DefaultTableModel(null, SspUploadConstants.UPLOAD_TABLE_COLUMN_NAME));
        jPanelConfig = new JPanel();
        jPanelConfig.add(new Box(BoxLayout.Y_AXIS) {{
            this.add(SspUtils.addFieldBox("COOKIE   : ", jTextFieldCookie = new JTextField(32)));
            this.add(SspUtils.addFieldBox("TOKEN    : ", jTextFieldToken = new JTextField(32)));
            this.add(SspUtils.addFieldBox("OP USER  : ", jTextFieldOpUser = new JTextField(32)));
            this.add(SspUtils.addFieldBox("OPT NAME : ", jTextFieldOptName = new JTextField(32)));
            this.add(SspUtils.addFieldBox("LOG ID   : ", jTextFieldLogId = new JTextField(32)));
            this.add(SspUtils.addFieldBox("APP KEY  : ", jTextFieldAppKey = new JTextField(32)));
            this.add(SspUtils.addFieldBox("SIGN     : ", jTextFieldSign = new JTextField(32)));
        }});
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jButtonChooser) {
            if (JFileChooser.APPROVE_OPTION == jFileChooser.showOpenDialog(this)) {
                SspUtils.runThread(this::fileChooser, "Thread-Chooser");
            }
        }
        if (e.getSource() == jButtonUpload) {
            SspUtils.runThread(this::fileUpload, "Thread-Upload");
        }
        if (e.getSource() == jButtonConfig) {
            this.saveConfig();
        }
    }

    public void fileChooser() {
        File dirFile = jFileChooser.getSelectedFile();
        String dirName = dirFile == null || !dirFile.exists() ? "" : dirFile.getName();
        String[] dirNames = dirName.split(",");
        if (dirFile == null || dirNames.length != SspUploadConstants.UPLOAD_FILE_NAME_LENGTH
                || dirNames[0].isEmpty() || dirNames[0].length() != SspUploadConstants.UPLOAD_FILE_NAME_DATE_LENGTH
                || dirNames[1].isEmpty()) {
            JOptionPane.showMessageDialog(this, "选择的监播文件目录错误！（年-月-日,订单号）", jButtonChooser.getText(), JOptionPane.ERROR_MESSAGE);
            return;
        }
        config = this.readConfig();
        config.setFile(dirFile.getAbsolutePath());
        config.setDate(dirNames[0]);
        config.setOrderId(dirNames[1]);
        jButtonChooser.setEnabled(false);
        tableModelUpload.setRowCount(0);
        File[] files = dirFile.listFiles();
        for (int i = 0; files != null && i < files.length; i++) {
            if (!files[i].isFile() || !Arrays.asList("xls", "xlsx").contains(FilenameUtils.getExtension(files[i].getName()))) {
                continue;
            }
            tableModelUpload.addRow(new Object[]{files[i], FilenameUtils.getBaseName(files[i].getName()), Boolean.FALSE, ""});
            jLabelStatus.setText(String.format(SspUploadConstants.UPLOAD_STATUS, config.getDate(), config.getOrderId(), tableModelUpload.getRowCount(), 0, 0));
        }
        jButtonChooser.setEnabled(true);
    }

    public void fileUpload() {
        if (config == null) {
            JOptionPane.showMessageDialog(this, "请先选择监播文件目录！", jButtonUpload.getText(), JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (config.isEmpty()) {
            JOptionPane.showMessageDialog(this, "参数配置不完整！", jButtonUpload.getText(), JOptionPane.ERROR_MESSAGE);
            jButtonConfig.doClick();
            return;
        }
        if (JOptionPane.OK_OPTION != JOptionPane.showConfirmDialog(this, String.format(SspUploadConstants.UPLOAD_INFO, config.getDate(), config.getOrderId()), jButtonUpload.getText(), JOptionPane.YES_NO_OPTION)) {
            return;
        }
        jButtonChooser.setEnabled(false);
        jButtonUpload.setEnabled(false);
        SspUploadManager manager = new SspUploadManager(config);
        jLabelStatus.setText("正在查询全部POI请稍后...");
        Map<String, String> allPoi = null;
        try {
            allPoi = manager.queryMonitInfo();
            System.out.println("查询全部POI数量：" + (allPoi == null ? 0 : allPoi.size()));
        } catch (Exception e) {
            System.err.println("查询全部POI异常：" + e.getMessage());
        }
        int ok = 0, no = 0;
        long ms = System.currentTimeMillis();
        System.out.println("上传开始：" + tableModelUpload.getRowCount());
        for (int i = 0; i < tableModelUpload.getRowCount(); i++) {
            File file = (File) tableModelUpload.getValueAt(i, 0);
            if ((Boolean) tableModelUpload.getValueAt(i, 2)) {
                ok++;
                continue;
            }
            int row = i;
            SwingUtilities.invokeLater(() -> {
                jTableUpload.setRowSelectionInterval(row, row);
                jTableUpload.scrollRectToVisible(jTableUpload.getCellRect(row, 0, true));
            });
            long mss = System.currentTimeMillis();
            System.out.println(i + ".上传开始：" + file);
            try {
                manager.upload(file, allPoi);
                tableModelUpload.setValueAt(Boolean.TRUE, i, 2);
                tableModelUpload.setValueAt("", i, 3);
                ok++;
            } catch (Exception ex) {
                System.err.println(i + ".上传异常：" + ex.getMessage());
                tableModelUpload.setValueAt(Boolean.FALSE, i, 2);
                tableModelUpload.setValueAt(ex.getMessage(), i, 3);
                no++;
            }
            System.out.println(i + ".上传完成：" + (System.currentTimeMillis() - mss));
            jLabelStatus.setText(String.format(SspUploadConstants.UPLOAD_STATUS, config.getDate(), config.getOrderId(), tableModelUpload.getRowCount(), ok, no));
        }
        System.out.println("上传完成：" + (System.currentTimeMillis() - ms));
        jButtonChooser.setEnabled(true);
        jButtonUpload.setEnabled(true);
    }

    public void saveConfig() {
        SspUploadConfig config = this.readConfig();
        if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(this, jPanelConfig, jButtonConfig.getText(), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE)) {
            this.writeConfig(config);
        }
    }

    public SspUploadConfig readConfig() {
        SspUploadConfig config = new SspUploadConfig();
        if (SspUploadConstants.UPLOAD_CONFIG_FILE.exists()) {
            try {
                config = JSON.parseObject(FileUtils.readFileToByteArray(SspUploadConstants.UPLOAD_CONFIG_FILE), SspUploadConfig.class);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "读取配置失败！(" + e.getMessage() + ")", jButtonConfig.getText(), JOptionPane.ERROR_MESSAGE);
            }
        }
        jTextFieldCookie.setText(config.getCookie());
        jTextFieldToken.setText(config.getToken());
        jTextFieldOptName.setText(config.getOptName());
        jTextFieldOpUser.setText(config.getOpUser());
        jTextFieldLogId.setText(config.getLogId());
        jTextFieldAppKey.setText(config.getAppKey());
        jTextFieldSign.setText(config.getSign());
        return config;
    }

    public void writeConfig(SspUploadConfig config) {
        config.setCookie(jTextFieldCookie.getText());
        config.setToken(jTextFieldToken.getText());
        config.setOptName(jTextFieldOptName.getText());
        config.setOpUser(jTextFieldOpUser.getText());
        config.setLogId(jTextFieldLogId.getText());
        config.setAppKey(jTextFieldAppKey.getText());
        config.setSign(jTextFieldSign.getText());
        try {
            FileUtils.writeByteArrayToFile(SspUploadConstants.UPLOAD_CONFIG_FILE, JSON.toJSONBytes(config));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "保存配置失败！(" + e.getMessage() + ")", jButtonConfig.getText(), JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) throws Exception {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        new SspUploadToolsGui().setVisible(true);
    }
}
